package com.hdl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import com.alibaba.fastjson.util.UTF8Decoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.IOException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

/**
 * 类名 RpcDecode
 * 描述 TODO
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/10 11:46
 */
public class RpcDecode extends ByteToMessageDecoder {
    private Class<?> clazz;

    private Serializer serializer;

    private String allMsg = "";

    public RpcDecode(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("decode invoke ");
        int len = byteBuf.readableBytes();
        if (len < 1) {
            return;
        }
        try {
            byte[] bytes = new byte[len];
            if (byteBuf.isReadable()){
                byteBuf.readBytes(bytes);
                System.out.println(new String(bytes, StandardCharsets.UTF_8));
                Object o = serializer.deserialize(clazz, bytes);
                if (o != null){
                    System.out.println("解析数据为JSON成功");
                    list.add(o);
                }else {
                    System.out.println("解析JSON数据失败!");
                    allMsg += new String(bytes, StandardCharsets.UTF_8);
                    System.out.println(allMsg);
                }
            }
        } catch (IOException e) {
            // 再次读取
            System.out.println("异常处理中-读取数据不是JSON");
            e.printStackTrace();
        }
    }

}
